/**
 * 
 */
package cn.ivicar.app.controller.event;

import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.codehaus.plexus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.ws.model.CustomerVehicle;
import cn.com.carsmart.ws.model.Vehicle;
import cn.ivicar.app.controller.service.CustomerVehicleService;
import cn.ivicar.app.controller.service.VehicleService;
import cn.ivicar.app.controller.util.DateUtil;
import cn.ivicar.message.push.controller.PushController;
import cn.ivicar.message.push.utils.EventCategoryEnum;
import net.sf.json.JSONObject;

/**
 * 管理告警信息
 * @author liurunbin 2017年7月9日 cn.ivicar.message.push.controller
 */
public class EventController {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(EventController.class);

	public static final Integer WORKER_NUMBER = 10;
	public static ExecutorService threadPool = Executors.newFixedThreadPool(WORKER_NUMBER);
	@Inject
	private PushController pushController;
	@Inject
	private VehicleService VehicleService;
	@Inject
	private CustomerVehicleService customerVehicleService;

	public void process(final JSONObject receive) {

		threadPool.execute(new Runnable() {

			@Override
			public void run() {
				try {
					processEvent(receive);
				} catch (CarsmartException e) {
					LOGGER.info("告警消息处理失败", e);
					e.printStackTrace();
				}

			}
		});

	}
    /*
    处理告警信息
     */
	public void processEvent(JSONObject receive) throws CarsmartException {

		if (receive == null) {
			LOGGER.info("告警消息为空，不再处理");
			return;
		}

		String event = receive.optString("event");
		if (StringUtils.isBlank(event)) {
			LOGGER.info("告警消息event字段为空，不再处理");
			return;
		}

		EventCategoryEnum categoryEnum = EventCategoryEnum.getByCloud(event);
		if (categoryEnum == null) {
			LOGGER.info("告警消息[event:%s]字段不合法，不再处理");
			return;
		}

		int category = categoryEnum.getIndex();
		String clientId = receive.optString("clientId");

		Vehicle v = VehicleService.getBySerial(clientId);
		if (v == null) {
			LOGGER.info(String.format("[clientId:%s]在系统没有对应的车辆，不再处理", clientId));
			return;
		}

		List<CustomerVehicle> list = customerVehicleService.getByVehicleId(v.getId(), null);
		if (list == null || list.isEmpty()) {
			LOGGER.info(String.format("[clientId:%s]在系统没有对应的customer，不再处理", clientId));
			return;
		}

		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(receive.optLong("time"));
		String time = DateUtil.TIMEFORMATER1().format(c.getTime());

		JSONObject type = new JSONObject();
		type.put("type", category);
		String vehicelNane = v.getName() == null ? "" : v.getName();
		String license = v.getLicensePlate() == null ? "" : v.getLicensePlate();
		String from = String.format("车辆名称:%s 车牌号:%s", vehicelNane, license);
		String message = category == EventCategoryEnum.SHAKE.getIndex() ? "车辆发生振动"
				: category == EventCategoryEnum.VOLTAGE.getIndex() ? "车辆电压过低" : "";
		String alert = message + "\n" + from;

		for (CustomerVehicle cv : list) {

			JSONObject pushparams = new JSONObject();
			pushparams.put("user_id", cv.getCustomerId());
			pushparams.put("car_serial", clientId);
			pushparams.put("real_message", type.toString());
			pushparams.put("car_name", vehicelNane);
			pushparams.put("car_license", license);
			pushparams.put("time", time);
			pushparams.put("from", from);
			pushparams.put("message", message);
			pushparams.put("alert", alert);

			pushController.process(pushparams);
		}
		LOGGER.info(String.format("告警消息[clientId:%s]处理完毕", clientId));

	}

}
